/**
 * 路由核心中间件
 * @author xiaoqiang <465633678@qq.com>
 * @created 2018/10/30 22:06:12
 */
const routes = require('./config')
const render = require('./render')
// 暂存递归路由
const transRoutes = []

/**
 * 
 * @param {Array} _routes 路由数组
 * @param {String} path 路径由父传子
 */
async function parseRoutes(_routes, path) {
  _routes.forEach(v => {
    /**
     * 判断是否有path,
     * 并且路径最后一位是否有'/'
     */
    if (path) {
      console.log(path.length, path[path.length-1] === '/')
      if (path[path.length-1] === '/') {
        let rPath = path + v.path
        v.path = rPath
        console.log(v.path)
      } else {
        v.path = path + '/' + v.path 
      }
    }
    /**
     * 判断路由是否又child属性
     * 有子路由则递归调用
     */
    if (v.child && v.child.length) {
      parseRoutes(v.child, v.path)
    }
    // 添加至路由表
    transRoutes.push({
      path: v.path,
      template: v.template
    })
    console.log(`路由${v.path}已添加..`)
  })
}
parseRoutes(routes)
/**
 * 路由中间件
 */
function routerMiddleware() {
  return async function (ctx, next) {
    try {
      // console.log(ctx)

      const route = transRoutes.filter(v => v.path === ctx.request.url)
      if (route.length) {
        // console.log(route)
        ctx.body = await render(route[0].template)
      } else {
        ctx.body = '404 not found'
      }
      await next()
    } catch (e) {
      throw new Error(e.message)
    }
  }
}
module.exports = routerMiddleware